package servlets;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import managers.JsonHelper;
import managers.SignedRequestsHelper;

public class SearchImage extends HttpServlet{
	private static final long serialVersionUID = 1L;
	private static final String AWS_ACCESS_KEY_ID = "AKIAIWIOLZ7WSLYBCSEA";
	private static final String AWS_SECRET_KEY = "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";
	private static final String ENDPOINT = "webservices.amazon.co.uk";
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) {
		String itemID = request.getParameter("id");
		JsonHelper jsonHelper = new JsonHelper();
		JSONObject root = new JSONObject(), imageSet = new JSONObject();
		JSONArray set = new JSONArray();
		
		SignedRequestsHelper helper;
        try {
            helper = SignedRequestsHelper.getInstance(ENDPOINT, AWS_ACCESS_KEY_ID, AWS_SECRET_KEY);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        
        String requestUrl = null;
        
        Map<String, String> params = new HashMap<String, String>();
        params.put("Service", "AWSECommerceService");
        params.put("Version", "2011-08-01");
        params.put("Operation", "ItemLookup");
        params.put("ItemId", itemID);
        params.put("AssociateTag", "wwwmarcoden-21");
        params.put("ResponseGroup", "Images");
        
        requestUrl = helper.sign(params);
        
        try {
        	root = jsonHelper.fromXMLtoJson(requestUrl);
        	System.out.println(root.toString());
        	JSONObject itemLookupResponse = root.getJSONObject("ItemLookupResponse");
        	JSONObject items = itemLookupResponse.getJSONObject("Items");
        	JSONObject item = items.getJSONObject("Item");
        	JSONObject imageSets = item.getJSONObject("ImageSets");
        	System.out.println("HERE");
        	try {
        		imageSet = imageSets.getJSONObject("ImageSet");
        	} catch(Exception e) {
        		imageSet = imageSets.getJSONArray("ImageSet").getJSONObject(0);
        	}
        	JSONObject mediumImage = imageSet.getJSONObject("MediumImage");
        	
        	String result = mediumImage.getString("URL");
        	
        	response.setContentType("application/json");
			response.setCharacterEncoding("UTF-8");
        	response.getWriter().write(result);
        } catch(Exception e) {
        	e.printStackTrace();
        }
	}

}
